package com.hbpa.pan.web.validator;

import com.hbpa.pan.core.constants.RPanConstants;
import lombok.extern.log4j.Log4j2;
import org.hibernate.validator.HibernateValidator;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

/**
 * @author: BlcakTiger
 * @date: 2023/10/15 15:02
 * @contact: hsf6661@163.com
 * @description: 统一的参数校验器
 */
@SpringBootConfiguration
@Log4j2
public class WebValidatorConfig {

    /**
     * 快速失败key(固定值)
     */
    private static final String FAIL_FAST_KEY = "hibernate.validator.fail_fast";

    /**
     * validator校验方法的后置处理器(方法级别的参数校验)
     * MethodValidationPostProcessor 是 Spring 的一个后处理器，用于启用方法参数校验。
     * @return
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor(){
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        //将自定义的验证器 rPanValidator() 与后处理器关联。这个验证器将用于验证方法的参数。
        postProcessor.setValidator(rPanValidator());
        log.info("The hibernation validator is loaded successfully!");
        return postProcessor;
    }

    /**
     * 构建rPan项目的方法参数校验器
     * @return
     */
    private Validator rPanValidator() {
        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure()
                //第一个验证失败时停止验证。
                .addProperty(FAIL_FAST_KEY, RPanConstants.TRUE_STR)
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }
}
